<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="80px">
      <el-form-item label="订单编号" prop="refOid">
        <el-input
          v-model="queryParams.refOid"
          placeholder="请输入订单编号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="店铺" prop="d3PosCode">
        <el-select v-model="queryParams.d3PosCode" placeholder="请选择店铺" size="small" clearable>
          <el-option
            v-for="item in shops"
            :key="item.id"
            :label="item.name"
            :value="item.code"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="Erp订单号" prop="sellformCode">
        <el-input
          v-model="queryParams.sellformCode"
          placeholder="请输入Erp订单号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="产品大类" prop="productType">
        <el-select v-model="queryParams.productType" placeholder="请选择" size="small" clearable>
          <el-option v-for="dict in productTypeList" :value="dict.dictValue" :label="dict.dictLabel" :key="dict.dictCode"/>
        </el-select>
      </el-form-item>
      <el-form-item label="发货地址" prop="logisticsSendFrom">
        <el-input v-model="queryParams.logisticsSendFrom" placeholder="请输入发货地址" clearable size="small" @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="发货时间" prop="beginTime">
        <el-date-picker clearable size="small" v-model="queryParams.beginTime" placeholder="请选择开始时间" type="date" value-format="yyyy-MM-dd">
        </el-date-picker>
        <el-date-picker clearable size="small" value-format="yyyy-MM-dd" type="date" placeholder="请选择结束时间" v-model="queryParams.endTime">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-table v-loading="loading" :data="groupList" border :summary-method="getSummaries" show-summary>
      <el-table-column label="Erp物料名称" align="center" prop="spName" width="600"/>
      <el-table-column label="数量" align="center" prop="num"/>
    </el-table>
    <div>
      <p>电商订单数量：{{sumObj}}</p>
      <p style="margin-left: 40%;margin-top: -34px">订单商品数量：{{sumItemObj}}</p>
    </div>

    <el-row :gutter="10" class="mb8">
    </el-row>

    <el-table v-loading="loading" :data="pushList" border :span-method="objectSpanMethod" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="35" align="center" />
      <el-table-column label="订单编号" align="center" prop="refOid" width="120"/>
      <el-table-column label="订单发货时间" align="center" prop="shippingTime" width="140"/>
      <el-table-column label="发货地址" align="center" prop="logisticsSendFrom" width="65"/>
<!--      <el-table-column label="店铺名称" align="center" prop="posName" />-->
      <el-table-column label="商品名称" align="center" prop="d3OiTitle" width="300" />
      <el-table-column label="商品规格" align="center" prop="d3OiStandards" width="300" />
      <el-table-column label="Erp订单号" align="center" prop="sellformCode" width="60"/>
      <el-table-column label="Erp物料名称" align="center" prop="spName"/>
      <el-table-column label="Erp物料数量" align="center" prop="num" width="50" />
<!--      <el-table-column label="单价" align="center" prop="singleFee" width="45" />-->
<!--      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">-->
<!--        <template slot-scope="scope">-->
<!--          <el-button-->
<!--            v-if="scope.row.isToSellform != 1"-->
<!--            size="mini"-->
<!--            type="text"-->
<!--            icon="el-icon-delete"-->
<!--            @click="handleDelete(scope.row)"-->
<!--            v-hasPermi="['d3:order:remove']"-->
<!--          >删除</el-button>-->
<!--        </template>-->
<!--      </el-table-column>-->
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <!-- 添加或修改对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="订单id" prop="refoid">
          <el-input v-model="form.refoid" placeholder="请输入订单id" />
        </el-form-item>
        <el-form-item label="店铺编码" prop="poscode">
          <el-input v-model="form.poscode" placeholder="请输入店铺编码" />
        </el-form-item>
        <el-form-item label="平台类型" prop="reftype">
          <el-select v-model="form.reftype" placeholder="请选择平台类型">
            <el-option label="请选择字典生成" value="" />
          </el-select>
        </el-form-item>
        <el-form-item label="旗帜" prop="flag">
          <el-input v-model="form.flag" placeholder="请输入旗帜" />
        </el-form-item>
        <el-form-item label="卖家备注" prop="sellermemo">
          <el-input v-model="form.sellermemo" placeholder="请输入卖家备注" />
        </el-form-item>
        <el-form-item label="买家留言" prop="buyermemo">
          <el-input v-model="form.buyermemo" placeholder="请输入买家留言" />
        </el-form-item>
        <el-form-item label="订单状态：">
          <el-radio-group v-model="form.status">
            <el-radio label="1">请选择字典生成</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="订单售后状态：">
          <el-radio-group v-model="form.refundstatus">
            <el-radio label="1">请选择字典生成</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="收件人国家" prop="receivercountry">
          <el-input v-model="form.receivercountry" placeholder="请输入收件人国家" />
        </el-form-item>
        <el-form-item label="收件人省" prop="receiverstate">
          <el-input v-model="form.receiverstate" placeholder="请输入收件人省" />
        </el-form-item>
        <el-form-item label="收件人市" prop="receivercity">
          <el-input v-model="form.receivercity" placeholder="请输入收件人市" />
        </el-form-item>
        <el-form-item label="收件人区/县" prop="receiverdistrict">
          <el-input v-model="form.receiverdistrict" placeholder="请输入收件人区/县" />
        </el-form-item>
        <el-form-item label="收件人镇" prop="receivertown">
          <el-input v-model="form.receivertown" placeholder="请输入收件人镇" />
        </el-form-item>
        <el-form-item label="应收金额" prop="totalfee">
          <el-input v-model="form.totalfee" placeholder="请输入应收金额" />
        </el-form-item>
        <el-form-item label="实付金额" prop="payment">
          <el-input v-model="form.payment" placeholder="请输入实付金额" />
        </el-form-item>
        <el-form-item label="实收金额" prop="receivedpayment">
          <el-input v-model="form.receivedpayment" placeholder="请输入实收金额" />
        </el-form-item>
        <el-form-item label="原价合计" prop="totalprice">
          <el-input v-model="form.totalprice" placeholder="请输入原价合计" />
        </el-form-item>
        <el-form-item label="售价合计" prop="totalsellprice">
          <el-input v-model="form.totalsellprice" placeholder="请输入售价合计" />
        </el-form-item>
        <el-form-item label="快递费用；包邮则是0" prop="postfee">
          <el-input v-model="form.postfee" placeholder="请输入快递费用；包邮则是0" />
        </el-form-item>
        <el-form-item label="服务费" prop="servicefee">
          <el-input v-model="form.servicefee" placeholder="请输入服务费" />
        </el-form-item>
        <el-form-item label="优惠金额" prop="discountfee">
          <el-input v-model="form.discountfee" placeholder="请输入优惠金额" />
        </el-form-item>
        <el-form-item label="下单时间" prop="ordertime">
          <el-input v-model="form.ordertime" placeholder="请输入下单时间" />
        </el-form-item>
        <el-form-item label="修改时间" prop="modifytime">
          <el-input v-model="form.modifytime" placeholder="请输入修改时间" />
        </el-form-item>
        <el-form-item label="支付时间" prop="paytime">
          <el-input v-model="form.paytime" placeholder="请输入支付时间" />
        </el-form-item>
        <el-form-item label="发货时间" prop="shippingtime">
          <el-input v-model="form.shippingtime" placeholder="请输入发货时间" />
        </el-form-item>
        <el-form-item label="完成时间" prop="finishtime">
          <el-input v-model="form.finishtime" placeholder="请输入完成时间" />
        </el-form-item>
        <el-form-item label="卖家昵称(淘宝平台返回)" prop="opensellernick">
          <el-input v-model="form.opensellernick" placeholder="请输入卖家昵称(淘宝平台返回)" />
        </el-form-item>
        <el-form-item label="买家昵称(淘宝平台返回)" prop="openbuyernick">
          <el-input v-model="form.openbuyernick" placeholder="请输入买家昵称(淘宝平台返回)" />
        </el-form-item>
        <el-form-item label="收货人id, 用于判断是否为同一个收货人" prop="receiverid">
          <el-input v-model="form.receiverid" placeholder="请输入收货人id, 用于判断是否为同一个收货人" />
        </el-form-item>
        <el-form-item label="买家OpenUid" prop="buyerOpenUid">
          <el-input v-model="form.buyerOpenUid" placeholder="请输入买家OpenUid" />
        </el-form-item>
        <el-form-item label="物流单号" prop="logisticsorderno">
          <el-input v-model="form.logisticsorderno" placeholder="请输入物流单号" />
        </el-form-item>
        <el-form-item label="对应销售订单状态">
          <el-radio-group v-model="form.sfStatus">
            <el-radio label="1">请选择字典生成</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import { listShop } from "@/api/d3/shop";
  import { listOrder, getOrder, delOrder, addOrder, updateOrder, exportOrder } from "@/api/d3/order";
  import {listToSellFormPc} from "@/api/d3/tosellform"
  import {getDicts} from '@/api/system/dict/data'

  export default {
  name: "PushData",
  components: {
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 推送数据列表
      pushList: [],
      //单品详情列表
      groupList:[],
      //合计列表
      getSum:[],
      //产品大类列表
      productTypeList:[],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      amount:0,
      sumObj:0,
      //订单电商产品数量
      sumItemObj:0,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        refOid: null,
        sellformCode: null,
        d3PosCode: null,
        beginTime:null,
        endTime: null,
        logisticsSendFrom:null,
        productType:null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        // receiverstate: [
        //   { required: true, message: "收件人省不能为空", trigger: "blur" }
        // ],
      },
      shops: [],
      OrderIndexArr:[],
    };
  },
  created() {
    this.getList();
    this.getShops();
    this.getDict();
  },
  methods: {
    getDict(){
      getDicts('category_pro_type').then(response=>{
        if (response.code==200){
          this.productTypeList=response.data;
        }
      })
    },
    /** 查询D3平台店铺列表 */
    getShops() {
      listShop().then(response => {
        this.shops = response.rows;
      });
    },

    getSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计：';
          return;
        }
        const values = data.map(item => Number(item[column.property]));
        if (!values.every(value => isNaN(value))) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              return prev + curr;
            } else {
              return prev;
            }
          }, 0);
          sums[index] += ' ';
        } else {
          sums[index] = 'N/A';
        }
      });

      return sums;
  },


    // 获取相同编号的订单
    gatherTableData() {
      let OrderObj = {}
      this.pushList.forEach((element, index) => {
        element.rowIndex = index
        if (OrderObj[element.refOid]) {
          OrderObj[element.refOid].push(index)
        } else {
          OrderObj[element.refOid] = []
          OrderObj[element.refOid].push(index)
        }
      })

      // 将数组长度大于1的值 存储到this.OrderIndexArr（也就是需要合并的项）
      this.OrderIndexArr = [];
      for (let k in OrderObj) {
        if (OrderObj[k].length > 1) {
          this.OrderIndexArr.push(OrderObj[k])
        }
      }
    },
    // 合并单元格
    objectSpanMethod({row,column,rowIndex,columnIndex}) {
      let colIndexs = [0,1,2,3,4];
      if (colIndexs.indexOf(columnIndex) > -1) {
        // if (this.OrderIndexArr && this.OrderIndexArr.length) {
          for (let i = 0; i < this.OrderIndexArr.length; i++) {
            let element = this.OrderIndexArr[i]
            for (let j = 0; j < element.length; j++) {
              let item = element[j]
              if (rowIndex == item) {
                if (j == 0) {
                  return {
                    rowspan: element.length,
                    colspan: 1
                  }
                } else if (j != 0) {
                  return {
                    rowspan: 0,
                    colspan: 0
                  }
                }
              }
            }
          // }
        }
      }
    },

    // //row当前行，column当前列，rowIndex当前行号，columnIndex当前列号
    // objectSpanMethod({ row, column, rowIndex, columnIndex }) {
    //   if (columnIndex === 1 || columnIndex === 2) {
    //     if (rowIndex % 2 === 0) {
    //       return {
    //         rowspan: 2,
    //         colspan: 1
    //       };
    //     } else {
    //       return {
    //         rowspan: 0,
    //         colspan: 0
    //       };
    //     }
    //   }
    // },

    /** 查询推送数据列表 */
    getList() {
      this.loading = true;
      if (this.queryParams.logisticsSendFrom==''){
        this.queryParams.logisticsSendFrom=null
      }
      listToSellFormPc(this.queryParams).then(response => {
        this.pushList = response.rows;
        this.groupList=response.sumObjGroupBy;
        this.getSum=response.rows;
        this.amount=response.amount;
        this.sumObj=response.sumObj;
        this.sumItemObj=response.sumItemObj;
        this.total = response.total;
        this.loading = false;
        this.gatherTableData();
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        refOid:null,
        sellformCode:null,
        d3OiTitle:null,
        d3OiStandards:null,
        spName:null,
        createTime: null,
        createBy: null,
        updateTime: null,
        updateBy: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加D3平台订单";
    },
    // /** 修改按钮操作 */
    // handleUpdate(row) {
    //   this.reset();
    //   const id = row.id || this.ids
    //   getOrder(id).then(response => {
    //     this.form = response.data;
    //     this.open = true;
    //     this.title = "修改D3平台订单";
    //   });
    // },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateOrder(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addOrder(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除该数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delOrder(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有D3平台订单数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportOrder(queryParams);
        }).then(response => {
          this.download(response.msg);
        })
    }
  }
};
</script>
